package com.fdb.efp.riskm.api.rest;

import com.alibaba.fastjson.JSON;
import com.fdb.efp.riskm.api.service.RiskmUtilService;
import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.basic.sequence.service.facade.SequenceService;
import com.fdb.efp.loan.service.facade.AccLoanService;
import com.fdb.efp.loan.service.vo.AccLoanVO;
import com.fdb.efp.riskm.common.ExcelException;
import com.fdb.efp.riskm.common.RiskColltConstant;
import com.fdb.efp.riskm.common.util.ExcelImportUtil;
import com.fdb.efp.riskm.service.facade.ColltResRecordService;
import com.fdb.efp.riskm.service.facade.ColltResRecordTempService;
import com.fdb.efp.riskm.service.facade.ColltTaskCommonService;
import com.fdb.efp.riskm.service.facade.ColltTaskInfoService;
import com.fdb.efp.riskm.service.vo.ColltResRecordVO;
import com.fdb.efp.riskm.service.vo.ColltTaskInfoVO;
import com.fdb.efp.riskm.service.vo.excelVo.ColltResRecordExcelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ColltResRecordController extends AbstractController {

	@Autowired
	@Qualifier("colltResRecordService")
	private ColltResRecordService colltResRecordService;

	@Autowired
	@Qualifier("colltResRecordTempService")
	private ColltResRecordTempService colltResRecordTempService;

	@Autowired
	@Qualifier("dbSeqService")
	private SequenceService sequenceService;

	@Autowired
	@Qualifier("colltTaskInfoService")
	private  ColltTaskInfoService colltTaskInfoService;

	@Autowired
	private RiskmUtilService riskmUtilService;

	@Autowired
	@Qualifier("colltTaskCommonService")
	private ColltTaskCommonService colltTaskCommonService;

    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;

	private static final String CONTENTTYPE = "application/json;charset=UTF-8";

	private static final String MODELNAME = "催收结果模板.xls";

	private static final String SHEETNAME = "催收结果";

	private static final String IMPORT_PATH = "/template/colltResultImport.xls";

	private List<String> recordSerno = new ArrayList<>();

	private List<String> errorTaskNoExcelVOList = new ArrayList<>();

	/**
	 * 列表数据查询【只查询本人的数据】
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/collt/res/records", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<ColltResRecordVO>> queryColltResRecordAll(@RequestBody ColltResRecordVO vo) {
		setUserInfoToVO(vo);
		List<ColltResRecordVO> outputVo = colltResRecordService.queryAllOwner(vo);
		riskmUtilService.displayOrgName(outputVo,"opOrgCode","opOrgName");
		riskmUtilService.displayUserName(outputVo,"opUserCode","opUserName");
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键查询详情
	 * @return
	 */
	@RequestMapping(value="/collt/res/record", method=RequestMethod.GET)
	public @ResponseBody ResponseData<ColltResRecordVO> queryByPk() {
		ColltResRecordVO inVo = new ColltResRecordVO();
		ColltResRecordVO outputVo = colltResRecordService.queryByPk(inVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键删除信息
	 * @param inColltResRecordVo
	 * @return
	 */
	@RequestMapping(value="/collt/res/record", method=RequestMethod.DELETE)
	public @ResponseBody
	ResponseData<Integer> deleteByPk(@RequestBody ColltResRecordVO inColltResRecordVo) {
		int outputVo = colltResRecordService.deleteByPk(inColltResRecordVo);
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键更新信息
	 * @param inColltResRecordVo
	 * @return
	 */
	@RequestMapping(value="/collt/res/record", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody ColltResRecordVO inColltResRecordVo) {
		int outputVo = colltResRecordService.updateByPk(inColltResRecordVo);
		return getResponseData(outputVo);

	}

	/**
	 * 新增数据
	 * @param inColltResRecordVo
	 * @return
	 */
	@RequestMapping(value="/collt/res/record", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertColltResRecord(@RequestBody ColltResRecordVO inColltResRecordVo) {
		int outputVo = 0;
		setUserInfoToVO(inColltResRecordVo);
		try {
			//判断还款金额是否等于借据逾期金额【目前只处理还款金额等于借据逾期金额的】
//			checkRepayLmt(inColltResRecordVo);

			inColltResRecordVo.setRecordSerno(getRecordSerno());
			inColltResRecordVo.setCreateUser(inColltResRecordVo.getLoginUserId());
			inColltResRecordVo.setCreateTime(TimeUtil.getCurrentDateTime());
			outputVo = colltResRecordService.insertColltResRecord(inColltResRecordVo);
			if(outputVo <= 0){
				throw new Exception("插入催收结果记录表失败！");
			}

			updColltTaskSts(inColltResRecordVo);

			return getResponseData(outputVo);
		} catch (Exception e) {
			e.printStackTrace();
			outputVo = -1;
			return ResponseData.create(outputVo, ApplicationConstance.FAILURE, e.getMessage(), false);
		}
	}

	/**
	 * 获取记录流水号
	 * @return
	 * @throws Exception
	 */
	private String getRecordSerno() throws Exception {
		String result = null;
		try {
			result = sequenceService.getSequence("RECORD_SEQ",null,null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("生成记录流水号失败，异常信息：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 判断还款金额是否等于借据逾期金额
	 * @param Vo
	 * @throws Exception
	 */
	private void checkRepayLmt(ColltResRecordVO Vo) throws Exception {
		ColltTaskInfoVO colltTaskInfoVO = new ColltTaskInfoVO();
		String colltTaskNo = Vo.getColltTaskNo();
		colltTaskInfoVO.setColltTaskNo(colltTaskNo);
		colltTaskInfoVO = colltTaskInfoService.queryByPk(colltTaskInfoVO);
		if(Objects.isNull(colltTaskInfoVO)){
			throw new Exception("通过催收任务编号:" + colltTaskNo + "，获取到的催收任务信息为空！");
		}
		if(colltTaskInfoVO.getOverLmt().compareTo(Vo.getRepayLmt()) != 0){
			throw new Exception("还款金额与逾期金额不相等，请核实后再操作！");
		}
		return;
	}

	/**
	 * 更新催收任务状态为结清c
	 * @param colltResRecordVO
	 * @throws Exception
	 */
	private void updColltTaskSts(ColltResRecordVO colltResRecordVO) throws Exception {
		ColltTaskInfoVO colltTaskInfoVO = new ColltTaskInfoVO();
		colltTaskInfoVO.setColltTaskNo(colltResRecordVO.getColltTaskNo());
		//根据借据信息判断当前任务状态
		BigDecimal unpdPrinBal = new BigDecimal("0");
		unpdPrinBal = colltTaskCommonService.getUnpdPrinBalByBillNo(colltResRecordVO.getLoanNo());
		if (BigDecimal.ZERO.compareTo(unpdPrinBal) == 0) colltTaskInfoVO.setTaskSts(RiskColltConstant.COLLT_OUTS_TASK_STS_03);
		else colltTaskInfoVO.setTaskSts(RiskColltConstant.COLLT_OUTS_TASK_STS_07);
//		colltTaskInfoVO.setTaskSts(RiskColltConstant.COLLT_OUTS_TASK_STS_03);
		int num = colltTaskInfoService.updateByPk(colltTaskInfoVO);
		if(num <= 0){
			throw new Exception("更新催收任务状态为结清失败！");
		}
	}


	/**
	 *  查询所有数据
	 *
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/3 17:23
	 * @date 2019/9/3 17:23
	 * @version 0.1
	 */
	@RequestMapping(value="/collt/res/record/infos", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<ColltResRecordVO>> queryAllOwner(@RequestBody ColltResRecordVO inColltResRecordVo) {
		List<ColltResRecordVO> outputVo = null;
		if(!StringUtil.isNullorBank(inColltResRecordVo.getExportFlag()) && "exp".equals(inColltResRecordVo.getExportFlag())) {
			logger.info("开始导出数据！");
			//获取逾期超过180天的催收任务信息
			ColltTaskInfoVO conditions = new ColltTaskInfoVO();
			conditions.setCusId(inColltResRecordVo.getCusId());
			List<ColltTaskInfoVO> taskInfos = colltTaskInfoService.queryExInfosOverdue(conditions);
			List<String> taskNos = taskInfos.stream().map(a->a.getColltTaskNo()).collect(Collectors.toList());
			outputVo = colltResRecordService.queryExAllOwner(taskNos);
		} else {
			logger.info("开始查询数据！");
			outputVo = colltResRecordService.queryAllOwner(inColltResRecordVo);
		}
		return getResponseData(outputVo);
	}

	/**
	 * 模板下载
	 *
	 * @author
	 * @version
	 * @since
	 */
	@RequestMapping(value = "/collt/res/record/template/downLoad", method = RequestMethod.GET)
	public @ResponseBody
	ResponseData<String> cusRelCherkModelDownLoad(HttpServletResponse response, HttpServletRequest request) throws IOException {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			response.setContentType(CONTENTTYPE);
			/**
			 * getBytes()，需要声明一下读取的编码方式，不然IE浏览器，会出现文件名乱码，谷歌不会
			 * 【解决方法】 getBytes("GBK")
			 */
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((MODELNAME).getBytes("GBK"), "ISO8859-1"));
			ServletOutputStream out = response.getOutputStream();
			logger.info("下载数据导入模板开始----------------------------");
			bis = new BufferedInputStream(ColltResRecordController.class.getClassLoader().getResourceAsStream(IMPORT_PATH));
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			logger.error("模板文件下载失败：", e);
			return getResponseData(null);
		} finally {
			if (null != bis) {
				bis.close();
			}
			if (null != bos) {
				bos.close();
			}
		}
		logger.info("下载关联人数据导入模板结束。。。。。。。。。。。。。。。。。。。");
		return getResponseData("success!");
	}

	/**
	 * 文件导入并解析储存到数据表
	 *
	 * @author
	 * @version
	 * @since
	 */
	@SuppressWarnings("resource")
	@RequestMapping(value = "/collt/res/record/temp/upload", method = RequestMethod.POST)
	public void colltResRecordMapUpload(HttpServletResponse respone, HttpServletRequest request) {
		ResponseData<List<ColltResRecordVO>> result = new ResponseData<List<ColltResRecordVO>>();
		List<File> cusRelCherkMapChecks = new ArrayList<File>();
		respone.setContentType(CONTENTTYPE);
		OutputStream out = null;
		try {
			out = respone.getOutputStream();
			//获取文件
			cusRelCherkMapChecks = riskmUtilService.getFileList(request);
			if (!cusRelCherkMapChecks.isEmpty()) {
				for (File file : cusRelCherkMapChecks) {
					//将Excel文件解析成对应实体Bean
					List<ColltResRecordExcelVO> colltResRecordExcelVOList = ExcelImportUtil.importExcelByClass(file, ColltResRecordExcelVO.class, SHEETNAME);

					colltResRecordExcelVOList.remove(0);//去掉样例数据20201121lmj

					//检校数据
					String errStr = "";
					errStr = checkDatas(colltResRecordExcelVOList);
					//组装数据
					List<ColltResRecordVO> inserColltResRecordMap = assembleData(colltResRecordExcelVOList);
					//执行插入操作
					execInsertSql(inserColltResRecordMap);
					//错误信息
					if (!StringUtil.isNullorBank(errStr)) {
						errStr = "ExcelError:" + errStr;
						throw new Exception(errStr);
					}
					//组装结果
					result = getResponseData(inserColltResRecordMap);
				}
			} else {
				throw new ExcelException("获取不到上传的文件！");
			}
		} catch (Exception e) {
			logger.error("文件上传失败,失败原因:", e);
			result = result.createData(null, ApplicationConstance.FAILURE, e.getMessage(), false);
		} finally {
			String str = JSON.toJSONString(result);
			try {
				out.write(str.getBytes(Charset.forName("UTF-8")));
				out.flush();
				out.close();
			} catch (IOException e) {
				logger.error("关闭数据流OutputStream出错，错误信息为：", e);
			}
		}
	}

	private String checkDatas(List<ColltResRecordExcelVO> colltResRecordExcelVOList) throws Exception {
		int errorRow = 3;
		errorTaskNoExcelVOList.clear();
		//记录存在空值行
		List<Integer> errorNullRowList = new ArrayList<>();
		String errorNullMsg = "";
		//记录excel数据填写重复行
		List<Integer> errorExcelDuplicateList = new ArrayList<>();
		String errorExcelDuplicateMsg = "";
		//记录一致性不通过的数据行
		List<Integer> errorConsistnetList = new ArrayList<>();
		String errorConsistnetMsg = "";
		//记录金额错误的信息
		/*List<Integer> errorLmtList = new ArrayList<>();
		String errorLmtMsg = "";*/
		//记录催收任务的任务状态不为“正常”的数据
		List<Integer> errorTaskStsList = new ArrayList<>();
		String errorTaskStsMsg = "";
		//记录已存在的历史数据行
//		List<Integer> errorDuplicateRowList = new ArrayList<>();
//		String errorDuplicateMsg = "";
        //记录借据信息是否存在拖欠本金
        List<Integer> errorLoanUnpdPriList = new ArrayList<>();
        String errorLoanUnpdPriMsg = "";
		//记录所有的错误提示信息
		Map<Integer, String> errorMap = new HashMap<Integer, String>();

		//统计excel表格里数据不为空的重复的“催收任务编号”
		List<String> excelDuplicateList = colltResRecordExcelVOList.stream()
				.filter(a -> !StringUtil.isNullorBank(a.getColltTaskNo()))
				.collect(Collectors.groupingBy(a -> a.getColltTaskNo(), Collectors.counting()))
				.entrySet().stream()
				.filter(entry -> entry.getValue() > 1)
				.map(entry -> entry.getKey())
				.collect(Collectors.toList());

		//查找任务信息
		List<String> taskNo = Optional.ofNullable(colltResRecordExcelVOList.stream().map(a->{return a.getColltTaskNo();}).collect(Collectors.toList())).orElseGet(ArrayList::new);
		List<ColltTaskInfoVO> queryRsColltTaskInfos = Optional.ofNullable(colltTaskInfoService.queryByTaskNo(taskNo)).orElseGet(ArrayList::new);
		List<ColltResRecordVO> queryRsColltResRecords = Optional.ofNullable(colltResRecordService.queryByTaskNo(taskNo)).orElseGet(ArrayList::new);

		for (ColltResRecordExcelVO item : colltResRecordExcelVOList) {
			//检查excel导入的数据是否存在为空的部分
			for (Field f : item.getClass().getDeclaredFields()) {
				f.setAccessible(true);
				if (f.get(item) == null) {
					errorNullRowList.add(errorRow);
					errorTaskNoExcelVOList.add(item.getColltTaskNo());
				}
			}
			//找出“催收任务编号”重复的行
			if (excelDuplicateList.contains(item.getColltTaskNo())) {
				errorExcelDuplicateList.add(errorRow);
				errorTaskNoExcelVOList.add(item.getColltTaskNo());
			}
			//数据一致性检校
			List<ColltTaskInfoVO> tempList = null;
			tempList = queryRsColltTaskInfos.stream()
					.filter(a -> a.getColltBatchNo().equals(item.getColltBatchNo())
							&& a.getCusId().equals(item.getCusId())
							&& a.getOutsOrgCode().equals(item.getOutsOrgCode())
							&& a.getColltWay().equals(item.getColltWay())
					)
					.collect(Collectors.toList());
			if (Objects.isNull(tempList) || tempList.isEmpty()) {
				errorConsistnetList.add(errorRow);
				errorTaskNoExcelVOList.add(item.getColltTaskNo());
			}
			//1.金额检校2.检查任务状态是否是正常的
			for (ColltTaskInfoVO info : queryRsColltTaskInfos) {
				//金额检校
				/*if (info.getColltTaskNo().equals(item.getColltTaskNo())){
					if (info.getOverLmt().compareTo(item.getRepayLmt()) != 0){
						errorLmtList.add(errorRow);
						errorTaskNoExcelVOList.add(item.getColltTaskNo());
					}
				}*/
				//检查任务状态是否存在审批流程
				if (info.getColltTaskNo().equals(item.getColltTaskNo())) {
					if (RiskColltConstant.COLLT_OUTS_TASK_STS_05.equals(info.getTaskSts()) || RiskColltConstant.COLLT_OUTS_TASK_STS_06.equals(info.getTaskSts())) {
						errorTaskStsList.add(errorRow);
						errorTaskNoExcelVOList.add(item.getColltTaskNo());
					}
				}
			}

			//检查是否已存在某个任务的催收结果
			/*for (ColltResRecordVO a:queryRsColltResRecords) {
				if (item.getColltTaskNo().equals(a.getColltTaskNo())) {
					errorDuplicateRowList.add(errorRow);
					errorTaskNoExcelVOList.add(item.getColltTaskNo());
				}
			}*/

            //记录借据信息是否存在拖欠本金
			AccLoanVO accLoanVO = new AccLoanVO();
			accLoanVO.setBillNo(item.getLoanNo());
            AccLoanVO queryRsAccLoanVO = accLoanService.queryByPk(accLoanVO);
            if (Objects.isNull(queryRsAccLoanVO)) {
                errorLoanUnpdPriList.add(errorRow);
                errorTaskNoExcelVOList.add(item.getColltTaskNo());
            } else if (queryRsAccLoanVO.getUnpdPrinBal() == null) {
                errorLoanUnpdPriList.add(errorRow);
                errorTaskNoExcelVOList.add(item.getColltTaskNo());
            }

			errorRow += 1;
		}
		//存在错误的信息的任务号去重
		errorTaskNoExcelVOList.stream().distinct().collect(Collectors.toList());

		if (errorNullRowList.size() > 0) {
			for (Integer integer : errorNullRowList) {
				errorNullMsg = "导入的Excel文档第【" + integer + "】行存在未填写数据！";
				logger.info("未填写：" + errorNullMsg);
				collError(errorMap,integer,errorNullMsg);
			}
		}

		if (errorExcelDuplicateList.size() > 0) {
			for (Integer integer : errorExcelDuplicateList) {
				errorExcelDuplicateMsg = "导入的Excel文档第【" + integer + "】行催收任务重复填写！";
				logger.info("重复填写：" + errorExcelDuplicateMsg);
				collError(errorMap,integer,errorExcelDuplicateMsg);
			}
		}

		if (errorConsistnetList.size() > 0) {
			for (Integer integer : errorConsistnetList) {
				errorConsistnetMsg = "导入的Excel文档第【" + integer + "】行数据一致性检校不通过！";
				logger.info("重复填写：" + errorConsistnetMsg);
				collError(errorMap,integer,errorConsistnetMsg);
			}
		}

		/*if (errorLmtList.size() > 0) {
			for (Integer integer : errorLmtList) {
				errorLmtMsg = "导入的Excel文档第【" + integer + "】行还款金额与逾期金额不相等！";
				logger.info("金额检校不通过，" + errorLmtMsg);
				collError(errorMap,integer,errorLmtMsg);
			}
		}*/

		if (errorTaskStsList.size() > 0) {
			for (Integer integer : errorTaskStsList) {
				errorTaskStsMsg = "导入的Excel文档第【" + integer + "】行数据在催收任务表相应的催收任务的任务状态不是正常！";
				logger.info("未填写：" + errorTaskStsMsg);
				collError(errorMap,integer,errorTaskStsMsg);
			}
		}

		/*if (errorDuplicateRowList.size() > 0) {
			for (Integer integer : errorDuplicateRowList) {
				errorDuplicateMsg = "导入的Excel文档第【" + integer + "】行的催收结果信息已存在！";
				logger.info("重复填写：" + errorDuplicateMsg);
				collError(errorMap,integer,errorDuplicateMsg);
			}
		}*/

        if (errorLoanUnpdPriList.size() > 0) {
            for (Integer integer : errorLoanUnpdPriList) {
                errorLoanUnpdPriMsg = "导入的Excel文档第【" + integer + "】行催收任务对应的借据信息没有“拖欠本金”！";
                logger.info("未填写：" + errorLoanUnpdPriMsg);
                collError(errorMap,integer,errorLoanUnpdPriMsg);
            }
        }

		//按key值对errorList排序并将value拼接成字符串
		String rs = "";
		rs += sortAndSpliceMap(errorMap);
		return rs;
		/*if (!StringUtil.isNullorBank(rs)) {
			rs = "ExcelError:" + rs;
			throw new Exception(rs);
		}*/
	}

	private void collError(Map<Integer, String> errorMap, Integer integer, String str) {
		if (errorMap.containsKey(integer)) {
			integer += 1;
			collError(errorMap,integer,str);
		} else {
			errorMap.put(integer,str);
		}
	}

	private String sortAndSpliceMap(Map<Integer, String> errorMap) {
		String rs = "";
		//取出key值，根据key值排序
		Object[] key = errorMap.keySet().toArray();
		Arrays.sort(key);
		//拼接信息
		Iterator ite = errorMap.entrySet().iterator();
		while (ite.hasNext()) {
			Entry string = (Entry) ite.next();
			StringBuffer buffer = new StringBuffer();
			if (StringUtil.isNullorBank(rs)) {
				rs = (String) string.getValue();
			} else {
				rs = buffer.append(rs).append(",").append(string.getValue()).toString();
			}
		}
		return rs;
	}

	private List<ColltResRecordVO> assembleData(List<ColltResRecordExcelVO> colltResRecordExcelVOList) throws Exception {
		//清空数据
		recordSerno.clear();
		List<ColltResRecordVO> list = new ArrayList<ColltResRecordVO>();
		if (Objects.nonNull(colltResRecordExcelVOList)) {
			Iterator<ColltResRecordExcelVO> iterator = colltResRecordExcelVOList.iterator();
			while (iterator.hasNext()) {
				ColltResRecordExcelVO tempExcelVO = iterator.next();
				ColltResRecordVO tempVO = new ColltResRecordVO();
				tempVO.setColltTaskNo(tempExcelVO.getColltTaskNo());
				tempVO.setColltBatchNo(tempExcelVO.getColltBatchNo());
				tempVO.setOutsOrgCode(tempExcelVO.getOutsOrgCode());
				tempVO.setOutsOrgName(tempExcelVO.getOutsOrgName());
				tempVO.setColltWay(tempExcelVO.getColltWay());
				tempVO.setCusId(tempExcelVO.getCusId());
				tempVO.setCusName(tempExcelVO.getCusName());
				tempVO.setLoanNo(tempExcelVO.getLoanNo());
//				tempVO.setRepayLmt(tempExcelVO.getRepayLmt() == null ? BigDecimal.ZERO : new BigDecimal(tempExcelVO.getRepayLmt()));
				tempVO.setRepayLmt(tempExcelVO.getRepayLmt());
				tempVO.setRepayDate(tempExcelVO.getRepayDate());
//				tempVO.setTaskSts(tempExcelVO.getTaskSts());
				tempVO.setColltResRemark(tempExcelVO.getColltResRemark());
				tempVO.setOpUserCode(tempExcelVO.getOpUserCode());
				tempVO.setOpOrgCode(tempExcelVO.getOpOrgCode());

				//判断是否有错误数据
				if (errorTaskNoExcelVOList.contains(tempExcelVO.getColltTaskNo())) {
					tempVO.setIsValid(BaseConstant.NO_N);
				} else {
					tempVO.setIsValid(BaseConstant.YES_Y);
				}

				tempVO.setRecordSerno(sequenceService.getSequence("RECORD_SEQ",null,null));
				list.add(tempVO);
				//记录“记录流水号”
				recordSerno.add(tempVO.getRecordSerno());
			}
			errorTaskNoExcelVOList.clear();
		} else {
			throw new ExcelException("获取数据为空!");
		}
		return list;
	}

	private void execInsertSql(List<ColltResRecordVO> inserColltResRecordMap) throws Exception {
		int num = 0;
		num = colltResRecordTempService.batchInsertIntoTemp(inserColltResRecordMap);
		if (num < 0) {
			throw new Exception("批量插入数据出错！请检查是否按照模板填写了正确的数据。");
		}
	}


	/**
	 * 根据主键批量删除信息
	 *
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/5 15:43
	 * @date 2019/9/5 15:43
	 * @version 0.1
	 */
	@RequestMapping(value="/collt/res/records", method=RequestMethod.DELETE)
	public @ResponseBody
	ResponseData<Integer> batchDeleteByPk(@RequestBody ColltResRecordVO inColltResRecordVo) {
		int outputVo = colltResRecordService.batchDeleteByPk(inColltResRecordVo);
		return getResponseData(outputVo);
	}

	/**
	 * 查询临时表所有当前导入的数据
	 *
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/3 17:23
	 * @date 2019/9/3 17:23
	 * @version 0.1
	 */
	@RequestMapping(value="/collt/res/record/temp/infos", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<ColltResRecordVO>> queryAllOwnerTempInfos(@RequestBody ColltResRecordVO inColltResRecordVo) {
		List<ColltResRecordVO> outputVo = null;
		inColltResRecordVo.setRecordSernoList(recordSerno);
		outputVo = colltResRecordTempService.queryAllOwnerTempInfos(inColltResRecordVo);
		riskmUtilService.displayOrgName(outputVo,"opOrgCode","opOrgName");
		riskmUtilService.displayUserName(outputVo,"opUserCode","opUserName");
		return getResponseData(outputVo);
	}
	/**
	 * 根据主键批量删除临时表信息
	 *
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/5 15:43
	 * @date 2019/9/5 15:43
	 * @version 0.1
	 */
	@RequestMapping(value="/collt/res/records/temp", method=RequestMethod.DELETE)
	public @ResponseBody
	ResponseData<Integer> batchDeleteTempByPk(@RequestBody ColltResRecordVO inColltResRecordVo) {
		int outputVo = colltResRecordTempService.batchDeleteByPk(inColltResRecordVo);
		return getResponseData(outputVo);
	}

	/**
	 * 清空临时表
	 *
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/9 20:43
	 * @date 2019/9/9 20:43
	 * @version 0.1
	 */
	@RequestMapping(value="/collt/res/all/temp", method=RequestMethod.DELETE)
	public @ResponseBody
	ResponseData<Integer> deleteAllTemp(@RequestBody ColltResRecordVO inColltResRecordVo) {
		int outputVo = colltResRecordTempService.deleteAllTemp(recordSerno);
		recordSerno.clear();
		return getResponseData(outputVo);
	}

	/**
	 * 将正确的临时数据批量存入正式表
	 *
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/10 8:48
	 * @date 2019/9/10 8:48
	 * @version 0.1
	 */
	@RequestMapping(value = "collt/res/temp/save", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertTemp2Formal(@RequestBody ColltResRecordVO inColltResRecordVo) throws Exception {
		int outputVo = 0;
		setUserInfoToVO(inColltResRecordVo);
		//用于暂存更新任务信息的数据
		List<ColltTaskInfoVO> colltTaskInfos = new ArrayList<>();
		//查找需要的信息
		List<ColltResRecordVO> confirmedInfos = null;
		confirmedInfos = colltResRecordTempService.queryByPKList(recordSerno);
		//存入创建相关信息
		for (ColltResRecordVO item:confirmedInfos) {
			//判断是否有无效的数据
			if (BaseConstant.NO_N.equals(item.getIsValid())) {
				confirmedInfos.remove(item);
				String message = "存在无效数据，请处理！";
				return ResponseData.create(outputVo, ApplicationConstance.FAILURE, message, false);
			}
			item.setCreateUser(inColltResRecordVo.getLoginUserId());
			item.setCreateTime(TimeUtil.getCurrentDateTime());

			//将必要信息存入更新任务信息的集合
			ColltTaskInfoVO temp = new ColltTaskInfoVO();
			//根据借据的"拖欠本金"，判断当前任务状态
			BigDecimal unpdPrinBal = colltTaskCommonService.getUnpdPrinBalByBillNo(item.getLoanNo());
			if (BigDecimal.ZERO.compareTo(unpdPrinBal) != -1) temp.setTaskSts(RiskColltConstant.COLLT_OUTS_TASK_STS_03);
			else temp.setTaskSts(RiskColltConstant.COLLT_OUTS_TASK_STS_07);
			temp.setColltTaskNo(item.getColltTaskNo());
			colltTaskInfos.add(temp);
		}
		//插入正式表

		if (Objects.isNull(confirmedInfos) || confirmedInfos.isEmpty()) {
			String message = "数据为空，请在有数据的情况下保存！";
			return ResponseData.create(outputVo, ApplicationConstance.FAILURE, message, false);
		} else {
			outputVo = colltResRecordService.batchInsertIntoFormal(confirmedInfos);
			if (outputVo < 0) {
				String message = "插入催收结果记录错误!";
				return ResponseData.create(outputVo, ApplicationConstance.FAILURE, message, false);
			}
		}
		//批量更新任务状态collt_task_info
		outputVo = colltTaskInfoService.batchUpdateVO(colltTaskInfos);
		if (outputVo < 0) {
			ColltResRecordVO tmp = new ColltResRecordVO();
			tmp.setRecordSernoList(recordSerno);
			colltResRecordService.batchDeleteByPk(tmp);
			String message = "更新催收信息错误!";
			return ResponseData.create(outputVo, ApplicationConstance.FAILURE, message, false);
		}
		return getResponseData(outputVo);
	}

}
